package server.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import server.HttpServlet;
import server.Request;
import server.Response;

import java.util.Map;

public class RequestHandler extends ChannelInboundHandlerAdapter {

    private Map<String, HttpServlet> servletMap;

    public RequestHandler(Map<String, HttpServlet> servletMap) {
        this.servletMap = servletMap;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;
            Response response = new Response(ctx, httpRequest);
            Request request = new Request(ctx, httpRequest);
            // 静态资源处理
            if (servletMap.get(request.getUri()) == null) {
                response.outputHtml(request.getUri());
            } else {
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUri());
                httpServlet.service(request, response);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

}
